package com.jinpeng.redis.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.jinpeng.redis.common.JsonUtil;
import com.jinpeng.redis.common.RedisUtil;
import com.jinpeng.redis.entity.User;
import com.jinpeng.redis.mapper.UserMapper;
import com.jinpeng.redis.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.lang.reflect.Type;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jp
 * @since 2020-01-07
 */
@Service
@CacheConfig(cacheNames="user")
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private  UserMapper userMapper;

    @Override
    @Cacheable
    public User selectUser(String id) {
        log.info("从数据库查询");
        return userMapper.selectById(id);
    }

    @Override
    public User insertUser(User user) {
        userMapper.insert(user);
        return user;
    }

    @Override
    public List<User> selectUserList() {
        List<User> users =  userMapper.selectList(null);
        redisUtil.set("userList", JsonUtil.obj2String(users));
        return users;
    }

    @Override
    public List<User> selectUserCacheList() {
        return JsonUtil.string2Obj(redisUtil.get("userList"), new TypeReference<List<User>>() {});
    }
}
